package com.cai.commons.utils;

import org.junit.Test;
import org.springframework.stereotype.Component;

import java.io.*;
@Component
public class IoUtils {
      private static String test=null;
      private static String result="";
    /**
     * @Author CWX
     * @Date 2017/7/23 19:53
     * 文件读取
     */
       public String reader(File file) throws IOException {
           FileReader fileReader=null;
           BufferedReader bufferedReader=null;
           try {
           fileReader=new FileReader(file);
           bufferedReader=new BufferedReader(fileReader);
           test=bufferedReader.readLine();
           if (test!=null) {
               //不为null第一行保存
               result += test;
               while (test != null) {//是否为空
                   test = null;//初始化后赋值
                   test = bufferedReader.readLine();
                   if (test != null) {//判断是否为空再加值
                       result += test;
                   }
               }
           }
           }catch (Exception e){
               System.out.println("io读取异常");
           }finally {
               //关闭资源
               bufferedReader.close();
               fileReader.close();
           }
           return result;
       }

    /**
     * @Author CWX
     * @Date 2017/7/23 19:54
     * 文件输出
     */
       public boolean writer(File dir,String fileName,String text) throws IOException {
           FileWriter fileWriter=null;
           BufferedWriter bufferedWriter=null;
           File file=new File(dir+"/"+fileName);
           if (!dir.exists()){//测试目录不存在
               dir.mkdirs();//创建新文件
               if (!file.exists()){
                   file.createNewFile();
               }else {
                   throw new IOException();
               }
           }
            try {
               fileWriter = new FileWriter(file);
               bufferedWriter=new BufferedWriter(fileWriter);
                bufferedWriter.write(text);
                bufferedWriter.flush();
                return true;
            }catch (Exception e){
                System.out.println("io输出异常");
                return false;
            }finally {
                //关闭资源
                bufferedWriter.close();
                fileWriter.close();

            }
       }
       public  void  inToOut(File input,File outputdir,String fileName) throws IOException {
           String text=reader(input);//读取
           writer(outputdir,fileName,text);//输入
       }
}
